from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
from graphy.backends import google_chart_api
import time
import math

class Pesada(db.Model):
  fecha=db.DateProperty(auto_now_add=True)
  peso=db.FloatProperty()
  cintura=db.FloatProperty()


class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/plain'
    salida="["
    pesadas = db.GqlQuery("SELECT * FROM Pesada ORDER BY fecha ASC LIMIT 10")
    primero=True
    for pesada in pesadas:
      if primero != True:
        salida = salida + ","
      primero=False
      salida=salida+"{fecha:"+str(pesada.fecha)+",peso:"+str(pesada.peso)+",cintura:"+str(pesada.cintura)+"}"
    salida=salida+"]"
    self.response.out.write(salida)

class InsertPage(webapp.RequestHandler):
  def post(self):
    self.response.headers['Content-Type'] = 'text/plain'
    pesada = Pesada()
    pesada.peso=float(self.request.get('peso'))
    pesada.cintura=float(self.request.get('cintura'))
    pesada.put()
    self.redirect('/')
    
class ChartTest(webapp.RequestHandler):
	def get(self):
		monthly_rainfall = [3.2, 3.2, 2.7, 0.9, 0.4, 0.1, 0.0, 0.0, 0.2, 0.9, 1.8, 2.3]
		months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
		chart = google_chart_api.LineChart(monthly_rainfall)
		chart.bottom.labels = months
		self.response.out.write(chart.display.Img(400, 100))
		
class ChartGenerator(webapp.RequestHandler):
	def post(self):
		#self.response.headers['Content-Type'] = 'image/png'
		pesadas = db.GqlQuery("SELECT * FROM Pesada ORDER BY fecha ASC LIMIT 10")
		if self.request.get('tipo')=='peso':
			pesos=[]
			fechas=[]
			for pesada in pesadas:
				pesos.append(pesada.peso)
				fechas.append(time.strftime('%d-%m-%Y',time.strptime(str(pesada.fecha), "%Y-%m-%d")))
			chart = google_chart_api.LineChart()
			chart.AddLine(pesos, label="Peso")
			chart.bottom.labels = fechas
			minimo = int(math.floor(min(pesos)-1))
			maximo = int(math.floor(max(pesos)+1))
			
			chart.left.min = minimo
			chart.left.max = maximo
			chart.left.labels = [minimo]+ pesos+ [maximo]
			chart.left.label_positions = [minimo]+ pesos+ [maximo]
			self.response.out.write(chart.display.Url(400, 300))
			#self.response.out.write(pesos)


application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/insertPeso', InsertPage),
                                      ('/testChart', ChartTest),
                                      ('/chartGenerator', ChartGenerator)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
